package team02.server.core.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

import team02.client.core.test.Test;
import team02.server.bean.TestBean;
import team02.server.bean.UserBean;
import team02.server.core.parser.CSVParser;
import team02.server.core.servlet.TestControllerDispatcher.RequestWrapper;
import team02.server.exception.ParserException;

public class UploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		processRequest(req, resp);
	}

	private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		RequestWrapper request = (RequestWrapper) req;
		try {
			processRequest0(request, resp);
		} catch (Exception e) {
			e.printStackTrace();
			if(e instanceof ParserException) {

				request.addParameter("result", e.getMessage());
			}else {
				
				request.addParameter("result", "エラー");
			}
			request.getRequestDispatcher("/jsp/uploadcsv.jsp").forward(req, resp);
		}
	}

	@SuppressWarnings("unchecked")
	private void processRequest0(RequestWrapper req, HttpServletResponse resp) throws FileUploadException, IOException,
			ParserException, ServletException, SQLException {
		// Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Parse the request
		List<FileItem> items = upload.parseRequest(req);

		for (FileItem item : items) {
			if (!item.isFormField()) {
				if (StringUtils.equals(item.getFieldName(), "csvfile")) {
					InputStream in = item.getInputStream();
					Test test = CSVParser.parseCSV(in);

					in.close();
					UserBean testMaker = (UserBean) req.getSession().getAttribute("userBean");
					test.setAlias(testMaker.getAlias());
					test.setCreatedBy(testMaker.getUserId());
					test.setCreatedTime(System.currentTimeMillis());
					String name = item.getName();
					int finalSlashPosition = Math.max(Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\') ), 0);
					test.setFileName(name.substring(finalSlashPosition));
					
					TestBean bean = new TestBean();
					bean.setTest(test);

					//kiểm tra xem bài test cũ với cùng tên đã có chưa
					String alias = ((UserBean)req.getSession().getAttribute("userBean")).getAlias();
					
					List<String> filenames = bean.listAllTestFileName(alias);
					for (String filename : filenames) {
						if(test.getFileName().equals(filename)) {
							bean.removeTestByName(alias, filename);
							break;
						}
					}
					try {
						if (bean.insert() == 0) {
							req.addParameter("result", "u=" + test.getCreatedBy() + "&t=" + test.getCreatedTime());
							req.getRequestDispatcher("/jsp/uploadcsv.jsp").forward(req, resp);
							return;
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}

		req.addParameter("result", "Unknown Error!");
		req.getRequestDispatcher("/jsp/uploadcsv.jsp").forward(req, resp);
	}
}
